<template>
  <div style="font-family:Simsun">
    <el-card>
      <template #header>
        <h2>重点人员管理</h2>
      </template>
      <el-form inline>
        <el-form-item label="姓名">
          <el-input v-model="queryForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="queryForm.idNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="warning" @click="resetList" >重置</el-button>
        </el-form-item>
        <el-form-item style="float: right; margin-right:10px">
          <el-button type="primary" @click="openAddKeyDialog">新增重点人员</el-button>
          <el-button type="danger"  @click="deleteMultipleKeys">删除</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" height="680" stripe border fit style="width: 100%" @selection-change="handleSelectionChange" ref="multipleTable">
        <el-table-column type="selection" width="55" />
        <el-table-column label="重点编号" align="center" prop="keyPersonId" width="90px" />
        <el-table-column label="姓名" align="center" prop="population.name" width="120px" />
        <el-table-column label="性别" align="center" prop="population.gender" width="200px" />
        <el-table-column label="身份证号码" align="center" prop="population.idNumber" width="200px" />
        <el-table-column label="人员类别" align="center" prop="category" />
        <el-table-column label="人员细别" align="center" prop="subCategory" />
        <el-table-column label="是否在控" align="center" prop="whetherInControl" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewDetails(scope.row)">详细</el-button>
            <el-button type="success" size="small" @click="editKey(scope.row)">编辑</el-button>
            <el-button type="danger" size="small"  @click="deleteSingleKey(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="demo-pagination-block" style="text-align: right;">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 详细信息弹窗 -->
      <el-dialog v-model="detailedInformationDFV" :title="dialogTitle" width="1050px">
        <el-form :model="detailData" label-width="120px">
          <div v-if="mode === 'add'" style="display: flex; align-items: flex-start;">
            <el-form-item label="搜索身份证号" style="flex: 1 0 42%;">
              <el-input v-model="queryForm.idNumber" placeholder="请输入身份证号"  />
            </el-form-item>
            <el-button type="primary" @click="searchByIdNumber" style="flex: 1 0 10%;margin-left: 15px">搜索</el-button>
            <el-form-item style="flex: 1 0 27%;">
            </el-form-item>
          </div>
          <div style="display: flex; flex-wrap: wrap;">
            <el-form-item label="姓名*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.name" :disabled="true" />
            </el-form-item>
            <el-form-item label="性别*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.gender" :disabled="true" />
            </el-form-item>
            <el-form-item label="出生日期*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.birthDate" :disabled="true" />
            </el-form-item>
            <el-form-item label="身份证号*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.idNumber" :disabled="true" />
            </el-form-item>
            <el-form-item label="户籍地址*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.householdAddress" :disabled="true" />
            </el-form-item>
            <el-form-item label="人员类别" style="flex: 1 0 33%;">
<!--              <el-input v-model="detailData.category" :disabled="mode === 'view'" />-->
              <el-cascader
                v-model="selectedValues"
                :options="options"
                clearable
                :placeholder="selectedValue"
                :disabled="mode === 'view'"
                style="flex: 1 0 33%;"
              />
            </el-form-item>
            <el-form-item label="民族*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.ethnicity" :disabled="true" />
            </el-form-item>
            <el-form-item label="文化程度*" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.educationLevel" :disabled="true" />
            </el-form-item>
            <el-form-item label="是否残疾" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.isDisabled" :disabled="true" />
            </el-form-item>
            <el-form-item label="是否在控*" style="flex: 1 0 33%;">
              <el-select
                v-model="detailData.whetherInControl"
                :disabled="mode === 'view'"
                style="flex: 1 0 33%;">
                <el-option
                  key="是"
                  label="是"
                  value="是"
                />
                <el-option
                  key="否"
                  label="否"
                  value="否"
                />
              </el-select>

            </el-form-item>
            <el-form-item label="血型" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.bloodType" :disabled="true" />
            </el-form-item>
            <el-form-item label="兵役状况" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.militaryStatus" :disabled="true" />
            </el-form-item>
            <el-form-item label="婚姻状况" style="flex: 1 0 33%;">
              <el-input v-model="detailData.population.maritalStatus" :disabled="true" />
            </el-form-item>
            <el-form-item label="重点人员编号" style="flex: 1 0 33%;">
              <el-input v-model="detailData.keyPersonId" :disabled="true" />
            </el-form-item>
            <el-form-item label="派出所" style="flex: 1 0 33%;">
              <el-input v-model="detailData.policeStation" :disabled="true" />
            </el-form-item>
            <el-form-item style="flex: 1 0 66%;">
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end;">
          <el-button v-if="mode === 'add'" @click="saveKey">保存</el-button>
          <el-button v-if="mode === 'edit'" @click="saveUpdateKey">更新</el-button>
          <el-button @click="detailedInformationDFV = false">关闭</el-button>
        </div>
      </el-dialog>
    </el-card>

  </div>
</template>

<script lang="ts" setup>
import { computed, Ref, ref, watch } from "vue";
import { getKeyList } from "../../../api/epgms/key/list.js";
import { updateKey } from "../../../api/epgms/key/update.js";
import { searchPopulationByIdNumber } from "../../../api/epgms/population/search.js";
import { deleteKey } from "../../../api/epgms/key/delete.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex';




const queryForm = ref({
  name: '',
  idNumber: '',
  pageNum: 1,
  pageSize: 10
});
const tableData = ref([]);
const total = ref(0);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const detailedInformationDFV = ref(false);
const dialogTitle = ref('');
const mode = ref('view'); // 用于区分是新增还是查看
const selectedRows = ref([]); // 存储选中的行
let searchIdNumber = ref('');
const selectedValues = ref<string[]>([]);
let selectedValue: string ;
const options = [
  {
    value: '涉恐人员',
    label: '涉恐人员',
    children: [
      {
        value: '恐怖组织成员',
        label: '恐怖组织成员',
      },
      {
        value: '恐怖主义嫌疑人',
        label: '恐怖主义嫌疑人',
      },
      {
        value: '恐怖活动支持者',
        label: '恐怖活动支持者',
      },
      {
        value: '恐怖主义嫌疑人',
        label: '恐怖主义嫌疑人',
      },
      {
        value: '受恐怖主义影响的人员',
        label: '受恐怖主义影响的人员',
      },
      {
        value: '其它涉恐人员',
        label: '其它涉恐人员',
      },
    ],
  },
  {
    value: '涉稳人员',
    label: '涉稳人员',
    children: [
      {
        value: '群体性事件参与者',
        label: '群体性事件参与者',
      },
      {
        value: '极端宗教活动参与者',
        label: '极端宗教活动参与者',
      },
      {
        value: '政治异见者',
        label: '政治异见者',
      },
      {
        value: '其它敏感人员',
        label: '其它敏感人员',
      },
    ],
  },
  {
    value: '涉毒人员',
    label: '涉毒人员',
    children: [
      {
        value: '吸毒人员',
        label: '吸毒人员',
      },
      {
        value: '贩毒人员',
        label: '贩毒人员',
      },
      {
        value: '制毒人员',
        label: '制毒人员',
      },
      {
        value: '毒品运输人员',
        label: '毒品运输人员',
      },
      {
        value: '涉毒未成年人',
        label: '涉毒未成年人',
      },
      {
        value: '其它涉毒人员',
        label: '其它涉毒人员',
      },
    ],
  },
  {
    value: '在逃人员',
    label: '在逃人员',
    children: [
      {
        value: '通缉犯',
        label: '通缉犯',
      },
      {
        value: '潜逃人员',
        label: '潜逃人员',
      },
      {
        value: '越狱逃犯',
        label: '越狱逃犯',
      },
      {
        value: '其它在逃人员',
        label: '其它在逃人员',
      },

    ],
  },
  {
    value: '重大刑事犯罪前科人员',
    label: '重大刑事犯罪前科人员',
    children: [
      {
        value: '暴力犯罪前科人员',
        label: '暴力犯罪前科人员',
      },
      {
        value: '财产犯罪前科人员',
        label: '财产犯罪前科人员',
      },
      {
        value: '其它重大犯罪前科人员',
        label: '其它重大犯罪前科人员',
      },
    ],
  },
  {
    value: '肇事精神病人',
    label: '肇事精神病人',
    children: [
      {
        value: '严重精神障碍患者',
        label: '严重精神障碍患者',
      },
      {
        value: '精神疾病发作期患者',
        label: '精神疾病发作期患者',
      },
      {
        value: '精神病史患者',
        label: '精神病史患者',
      },
      {
        value: '其它肇事精神病人',
        label: '其它肇事精神病人',
      },
    ],
  },
  {
    value: '重点上访人员',
    label: '重点上访人员',
    children: [
      {
        value: '长期上访人员',
        label: '长期上访人员',
      },
      {
        value: '群体性上访组织者',
        label: '群体性上访组织者',
      },
      {
        value: '重点案件上访人员',
        label: '重点案件上访人员',
      },
      {
        value: '其它重点上访人员',
        label: '其它重点上访人员',
      },
    ],
  },
]
// 响应式变量来存储级联选择器选中的值


let detailData = ref({
  population: {
    name: '',
    gender: '',
    idNumber: '',
    birthDate: '',
    maritalStatus: '',
    educationLevel: '',
    householdAddress: '',
    ethnicity: '',
    isDisabled: '',
    bloodType: '',
    militaryStatus: '',
    personId:''
  },
  keyPersonId: '',
  category:'',
  policeStation: '',
  businessType: '',
  subCategory:'',
  controlledStatus:'',
  whetherInControl:'',
  policeStationId:'',
});


const openAddKeyDialog = () => {
  mode.value = 'add';
  dialogTitle.value = '新增重点人口';
  detailedInformationDFV.value = true;
  selectedValue=''
  clearDetailData();
};
const editKey = (row) => {
  mode.value = "edit";
  dialogTitle.value = "编辑重点人员";
  detailData.value = { ...row };
  selectedValues.value = [row.category, row.subCategory];
  selectedValue=''
  selectedValue=row.category.toString()+" / "+row.subCategory.toString()
  detailedInformationDFV.value = true;
};

const viewDetails = (row: any) => {
  mode.value = 'view';
  dialogTitle.value = '重点人口信息';
  detailData.value = row;
  selectedValues.value = [row.category, row.subCategory];
  selectedValue=''
  selectedValue=row.category.toString()+" / "+row.subCategory.toString()
  console.log("------------====--------------------")
  console.log(selectedValues.value)
  detailedInformationDFV.value = true;
};
//监听级联选择器选中值的变化
watch(selectedValues, (newValues) => {
  detailData.value.category = newValues[0] || null;
  detailData.value.subCategory = newValues[1] || null;
}, { immediate: true });

const clearDetailData = () => {
  detailData.value = {
    population: {
      name: '',
      gender: '',
      idNumber: '',
      birthDate: '',
      maritalStatus: '',
      educationLevel: '',
      householdAddress: '',
      ethnicity: '',
      isDisabled: '',
      bloodType: '',
      militaryStatus: '',
      personId:''
    },
    keyPersonId: '',
    category:'',
    policeStation: '',
    businessType: '',
    subCategory: '',
    controlledStatus:'',
    whetherInControl:'',
    policeStationId:'',
  };
};

const officerInfo = useStore().getters.officerInfo;
const searchByIdNumber = async () => {
  const res = await searchPopulationByIdNumber({
    idNumber: queryForm.value.idNumber,
  });

  if (res.data.code === 2000 && res) {
    const person = res.data.data;
    detailData.value.population.personId=person.personId;
    detailData.value.population.name = person.name;
    detailData.value.population.gender = person.gender;
    detailData.value.population.idNumber = person.idNumber;
    detailData.value.population.birthDate = person.birthDate;
    detailData.value.population.householdAddress = person.householdAddress;
    detailData.value.population.ethnicity = person.ethnicity; // Assuming this is mapped correctly
    detailData.value.population.educationLevel = person.educationLevel;
    detailData.value.population.bloodType = person.bloodType; // This field is not in the response
    detailData.value.population.militaryStatus = person.militaryStatus; // This field is not in the response
    detailData.value.population.isDisabled = person.isDisabled;
    detailData.value.policeStation = officerInfo.policeStation.name; 
    detailData.value.keyPersonId = person.personId; 
    detailData.value.population.maritalStatus = person.maritalStatus;

  } else {
    console.error("Failed to fetch data or no matching record found");
  }
};


const saveKey = async () => {
  try {
    detailData.value.controlledStatus=detailData.value.whetherInControl === '是'?'1':'0'
    const res = await updateKey({
      personId : detailData.value.population.personId,
      subCategory : detailData.value.subCategory,
      controlledStatus:detailData.value.controlledStatus,
      category : detailData.value.category,
      policeStationId : "1"
    }); // 调用后端API保存重点人口信息

    if (res.data.code === 2000) {
      detailedInformationDFV.value = false;
      await fetchData(); // 保存成功后刷新列表数据
      ElMessage({
        message: '保存成功！',
        type: 'success',
      })
    } else {
      console.error('保存失败:', res.data.message || '未知错误')
      ElMessage.error('保存失败！')
    }
  } catch (error) {
    console.error('保存失败:', error.message || '未知错误');
    ElMessage.error('保存失败！')
  }
};
const saveUpdateKey = async () => {
  try {
    detailData.value.controlledStatus=detailData.value.whetherInControl === '是'?'1':'0'
    const res = await updateKey({
      personId : detailData.value.population.personId,
      subCategory : detailData.value.subCategory,
      controlledStatus:detailData.value.controlledStatus,
      category : detailData.value.category,
      policeStationId : "1",
      keyPersonId:detailData.value.keyPersonId
    }); // 调用后端API保存重点人口信息
    if (res.data.code === 2000) {
      detailedInformationDFV.value = false;
      await fetchData(); // 保存成功后刷新列表数据
      ElMessage({
        message: '更新成功！',
        type: 'success',
      })
    } else {
      console.error('更新失败:', res.data.message || '未知错误')
      ElMessage.error('更新失败！')
    }
  } catch (error) {
    console.error('更新失败:', error.message || '未知错误');
    ElMessage.error('更新失败！')
  }
};


// 删除单个重点人口
const deleteSingleKey = async (row: any) => {
  ElMessageBox.confirm(
    '您确定要删除这条数据?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const res = await deleteKey([row.keyPersonId]); // 调用后端API删除重点人口信息

        if (res.every(r => r.data.code === 2000)) {
          console.log('成功删除重点人口信息:', row);
          await fetchData(); // 删除成功后刷新列表数据
          ElMessage({
            message: '删除成功！',
            type: 'success',
          })
        } else {
          console.error('删除失败:', res[0].data.message || '未知错误');
          ElMessage.error('删除失败！')
        }
      } catch (error) {
        console.error('删除失败:', error.message || '未知错误');
        ElMessage.error('删除失败！')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })

};

const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
// 批量删除重点人口
const deleteMultipleKeys = async () => {

  ElMessageBox.confirm(
    '您确定要删除这几条数据?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.error('请选择需要删除的内容！')
        return;
      }
      const ids = selectedRows.value.map(row => row.keyPersonId);
      const res = await deleteKey(ids);

      if (res.every(r => r.data.code === 2000)) {
        console.log('成功批量删除重点人口信息:', ids);
        await fetchData(); // 删除成功后刷新列表数据
        ElMessage({
          message: '删除成功！',
          type: 'success',
        })
      } else {
        console.error('批量删除失败:', res[0].data.message || '未知错误');
        ElMessage.error('删除失败！')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
};
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val;
  fetchData();
};

const search = () => {
  queryForm.value.pageNum = 1; // 重置为第一页
  fetchData();
};
const resetList =()=>{
  queryForm.value.name=""
  queryForm.value.idNumber=""
  queryForm.value.pageNum=1
  queryForm.value.pageSize=10
  fetchData()
}
const fetchData = async () => {
  try {
    const res = await getKeyList({
      name: queryForm.value.name,
      idNumber: queryForm.value.idNumber,
      pageNum: queryForm.value.pageNum,
      pageSize: queryForm.value.pageSize
    });

    if (res && res.data.code === 2000 && res.data) {
      tableData.value = res.data.data.map(item => ({
        ...item,
        whetherInControl: item.controlledStatus === 1 ? '是' : '否'
      }));
      total.value = res.data.total;
      console.log('Fetched data:', tableData.value); // Debugging: log the fetched data
    } else {
      console.error("Failed to fetch data or data format is incorrect");
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

fetchData();
</script>

<style scoped>
.demo-pagination-block {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

::v-deep .el-form-item__label {
  color: #000000;
  font-size: 16px;
}

::v-deep .el-button el-button--primary{
  align-items: center;
}
</style>
